package com.zhang.springcloud.controller;

import com.zhang.springcloud.entities.CommonResult;
import com.zhang.springcloud.entities.Payment;
import com.zhang.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    PaymentService ps;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private DiscoveryClient dc;
    //@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)；GET方式无请求体，所以使用@RequestBody接收数据时，
    // 前端不能使用GET方式提交数据，而是用POST方式进行提交。在后端的同一个接收方法里，@RequestBody与@RequestParam()可以同时使用，
    // @RequestBody最多只能有一个，而@RequestParam()可以有多个。
    @PostMapping("/payment/add")
    public CommonResult create(@RequestBody Payment payment){
        int result = ps.create(payment);
        if(result > 0){
            return new CommonResult(200,"添加成功"+serverPort,result);
        }else{
            return new CommonResult(444,"添加失败"+serverPort,null);
        }
    }
    //啊啊啊啊
    @GetMapping("/payment/select/{id}")
    public CommonResult select(@PathVariable("id") Long id){
        Payment result = ps.getPaymentById(id);
        if(result != null){
            return new CommonResult(200,"查询成功"+serverPort,result);
        }else{
            return new CommonResult(444,"查询失败"+id+"  "+serverPort,null);
        }
    }
    @GetMapping("/payment/cover")
    public Object discover(){
        List<String> list = dc.getServices();
        for (String lis : list) {
            System.out.println("服务名: "+lis);
        }
        List<ServiceInstance> li = dc.getInstances("cloud-payment-service");
        for (ServiceInstance si:li) {
            System.out.println(si.getServiceId()+" "+si.getHost()+" "+si.getPort()+" "+si.getUri());
        }
        return this.dc;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/payment/feigntimeout")
    public String getFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
    @GetMapping("zipkin")
    public String paymentZipkin() {
        return "hi,i`am paymentzipkin server fall back.welcome to atguigu.hahahahahhahahah";
    }
}
